#include <iostream>
#include <fstream>
#include <string>
#include <cstring>
#include <winsock2.h>
#include <ws2tcpip.h>

#pragma comment(lib, "ws2_32.lib")

#define MULTICAST_GROUP "224.1.1.1"
#define PORT 8888
#define BUFFER_SIZE 1024 * 1024 // 1MB缓冲区，可根据实际情况调整

// 发送文件函数
void sendFile(const std::string& filePath) {
    WSADATA wsaData;
    if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
        std::cerr << "WSAStartup failed: " << WSAGetLastError() << std::endl;
        return;
    }

    SOCKET sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
    if (sock == INVALID_SOCKET) {
        std::cerr << "Socket creation failed: " << WSAGetLastError() << std::endl;
        WSACleanup();
        return;
    }

    sockaddr_in multicastAddr;
    multicastAddr.sin_family = AF_INET;
    multicastAddr.sin_port = htons(PORT);
    InetPton(AF_INET, MULTICAST_GROUP, &multicastAddr.sin_addr);

    // 设置套接字选项，允许发送多播数据
    int enable = 1;
    if (setsockopt(sock, IPPROTO_IP, IP_MULTICAST_TTL, (const char*)&enable, sizeof(enable)) == SOCKET_ERROR) {
        std::cerr << "Setsockopt failed: " << WSAGetLastError() << std::endl;
        closesocket(sock);
        WSACleanup();
        return;
    }

    std::ifstream file(filePath, std::ios::binary);
    if (!file) {
        std::cerr << "Failed to open file: " << filePath << std::endl;
        closesocket(sock);
        WSACleanup();
        return;
    }

    char buffer[BUFFER_SIZE];
    while (file.read(buffer, sizeof(buffer))) {
        if (sendto(sock, buffer, sizeof(buffer), 0, (sockaddr*)&multicastAddr, sizeof(multicastAddr)) == SOCKET_ERROR) {
            std::cerr << "Sendto failed: " << WSAGetLastError() << std::endl;
            break;
        }
    }
    // 发送剩余数据
    std::streamsize remaining = file.gcount();
    if (remaining > 0) {
        file.read(buffer, remaining);
        if (sendto(sock, buffer, remaining, 0, (sockaddr*)&multicastAddr, sizeof(multicastAddr)) == SOCKET_ERROR) {
            std::cerr << "Sendto failed: " << WSAGetLastError() << std::endl;
        }
    }

    file.close();
    closesocket(sock);
    WSACleanup();
}

// 接收文件函数
void receiveFile(const std::string& savePath) {
    WSADATA wsaData;
    if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
        std::cerr << "WSAStartup failed: " << WSAGetLastError() << std::endl;
        return;
    }

    SOCKET sock = socket(AF_INET, SOCK_DUDP, IPPROTO_UDP);
    if (sock == INVALID_SOCKET) {
        std::cerr << "Socket creation failed: " << WSAGetLastError() << std::endl;
        WSACleanup();
        return;
    }

    sockaddr_in localAddr;
    localAddr.sin_family = AF_INET;
    localAddr.sin_port = htons(PORT);
    localAddr.sin_addr.s_addr = INADDR_ANY;

    if (bind(sock, (sockaddr*)&localAddr, sizeof(localAddr)) == SOCKET_ERROR) {
        std::cerr << "Bind failed: " << WSAGetLastError() << std::endl;
        closesocket(sock);
        WSACleanup();
        return;
    }

    ip_mreq multicastRequest;
    multicastRequest.imr_multiaddr.s_addr = inet_addr(MULTICAST_GROUP);
    multicastRequest.imr_interface.s_addr = INADDR_ANY;

    if (setsockopt(sock, IPPROTO_IP, IP_ADD_MEMBERSHIP, (const char*)&multicastRequest, sizeof(multicastRequest)) == SOCKET_ERROR) {
        std::cerr << "Setsockopt failed: " << WSAGetLastError() << std::endl;
        closesocket(sock);
        WSACleanup();
        return;
    }

    std::ofstream file(savePath, std::ios::binary);
    if (!file) {
        std::cerr << "Failed to open file for writing: " << savePath << std::endl;
        closesocket(sock);
        WSACleanup();
        return;
    }

    char buffer[BUFFER_SIZE];
    sockaddr_in senderAddr;
    int senderAddrLen = sizeof(senderAddr);
    int bytesReceived;
    while ((bytesReceived = recvfrom(sock, buffer, sizeof(buffer), 0, (sockaddr*)&senderAddr, &senderAddrLen)) > 0) {
        file.write(buffer, bytesReceived);
    }

    file.close();
    closesocket(sock);
    WSACleanup();
}

int main() {
    // 示例：发送文件
    sendFile("large_file.exe");
    // 示例：接收文件
    receiveFile("received_file.exe");

    return 0;
}